from __future__ import absolute_import, unicode_literals

import logging
import os
from datetime import timedelta

from celery import Celery
from celery.schedules import crontab
from django.conf import settings

redis_url = "1.94.32.80"
redis_password = "weiqt"
redis_port = 6379
redis_task_db = 0
redis_result_db = 1

CELERY_BROKER_URL = f"redis://:{redis_password}@{redis_url}:{redis_port}/{redis_task_db}"
CELERY_RESULT_BACKEND = f'redis://:{redis_password}@{redis_url}:{redis_port}/{redis_result_db}'

# 指定Django默认配置文件模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Lab301.settings')

# 为我们的项目myproject创建一个Celery实例。这里不指定broker backend 容易出现错误。
# 如果没有密码 使用 'redis://127.0.0.1:6379/0'
app = Celery('Vjudge', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND)

# 这里指定从django的settings.py里读取celery配置
app.config_from_object('django.conf:settings')
# 下面的设置就是关于调度器beat的设置,
# 具体参考https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
# app.conf.beat_schedule = {
#     'autosc': {  # 取个名字
#         'task': 'user.tasks.auto_sc',  # 设置是要将哪个任务进行定时
#         'schedule': crontab(),  # 调用crontab进行具体时间的定义
#     },
# }
# 自动从所有已注册的django app中加载任务
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

app.conf.timezone = 'Asia/Shanghai'

logger = logging.getLogger(__name__)

app.conf.update(
    CELERYBEAT_SCHEDULE={
        'get_cf_problem_every_day': {
            'task': 'Admin.tasks.get_problem.get_cf_problems',  # 请替换为你的任务函数路径
            'schedule': timedelta(days=1),
            'args': (),  # 如果任务需要参数，请在这里提供
        },
        'check_member_training_every_night': {
            'task': 'check_member_training_task',
            'schedule': crontab(hour="23", minute="30"),
            'args': (),
        },
    }
)


@app.task(bind=True)
def debug_task(self, *args, **kwargs):
    print('Request: {0!r}'.format(self.request))


@app.task
def test(arg):
    print(arg)
